import 'package:xbaistack/consts.dart';
import 'package:xbaistack/l10n/app_localizations.dart';
import 'package:xbaistack/router.dart';
import 'package:flutter/material.dart';
import 'package:xbaistack/theme/theme_extension.dart';

extension Context on BuildContext {
  // 不带参数的跳转
  Future<T?> routeTo<T extends Object?>(Type router) {
    return MyRouter.routeTo(this, router);
  }

  // 通过这种方式，可以先获取页面对象的实例
  // 然后通过实例对象去调用 arguments 方法，最后调用 to 即可完成路由跳转
  RT routeOf<RT extends RouterBridge>() {
    assert(
      RT != RouterBridge<dynamic>,
      "You must specify the route type, for example: \"context.routeOf<Page>()\";",
    );
    return MyRouter.of<RT>(this);
  }

  void back([Object? arguments]) => Navigator.pop(this, arguments);
  void backHome() => Navigator.popUntil(this, (route) => route.isFirst);

  AppLocalizations get l10n => AppLocalizations.of(this);
  AppTheme get theme => AppTheme.of(this);
}

mixin Widgets {
  void refresh() {}
}

abstract class BaseStateessWidget<RT_ARG_TYPE> extends StatelessWidget
    with Widgets, RouterBridge<RT_ARG_TYPE> {
  const BaseStateessWidget({super.key});
  void onInitialize(BuildContext context) {}

  @override
  Widget build(BuildContext context) {
    onInitialize(context);
    return onCreate(context, argumentOf(context));
  }

  Widget onCreate(BuildContext context, RT_ARG_TYPE? arg) {
    return const SizedBox.shrink();
  }
}

//基础StatefulWidget
abstract class BasestatefulWidget<RT_ARG_TYPE> extends StatefulWidget
    with Widgets, RouterBridge<RT_ARG_TYPE> {
  const BasestatefulWidget({super.key});
}

//基础State类
abstract class Basestate<W extends BasestatefulWidget<RT_ARG_TYPE>, RT_ARG_TYPE>
    extends State<W> {
  void refresh() => rebuild();

  void rebuild([VoidCallback? callback]) {
    super.setState(callback ?? Consts.doNothing);
  }

  @override
  Widget build(BuildContext context) {
    return onCreate(context, widget.argumentOf(context));
  }

  Widget onCreate(BuildContext context, RT_ARG_TYPE? arg) {
    return const SizedBox.shrink();
  }
}

// 基础控制器
class BaseController<S extends State> {
  final GlobalKey<S> key = GlobalKey(debugLabel: "$S");
  bool get isReady => key.currentState != null && key.currentState!.mounted;
  S? get state => isReady ? key.currentState : null;
  void dispose() {}
}
